package com.thinkcoder.util.http;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 使用UrlConnection发送http请求
 *
 * @author 商俊帅
 * @date 2021/04/16 16:35
 **/
@Slf4j
public class UrlConnectionUtil {


    /***
     *发送get请求
     */
    public static String sendGetRequest(String getUrl){

        StringBuilder sb = new StringBuilder();
        HttpURLConnection urlConnection=null;
        InputStreamReader isr;
        BufferedReader br = null;
        try{
            URL url = new URL(getUrl);
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setAllowUserInteraction(false);
            isr = new InputStreamReader(url.openStream());
            br = new BufferedReader(isr);
            String line;
            while ((line=br.readLine())!=null){
                sb.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                //关闭包装流即可
                br.close();
            }catch (IOException e){
                log.error("get请求出错",e);
            }
            //固定多线程的话，如果不disconnect，链接会增多
            //直到收发不出信息。写上disconnect后正常一些
            urlConnection.disconnect();
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String s = sendGetRequest("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx845389d9debe8bdf&secret=0c38ad32c7632e3b050f698af2210e19&code=18832650890&grant_type=authorization_code");
        System.out.println(s);
    }

}
